﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace btnet.pages
{
    public partial class change_password : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            Bug_Util.set_context(HttpContext.Current);
            Bug_Util.do_not_cache(Response);

            if (!IsPostBack)
            {
                titl.Text = Bug_Util.get_setting("AppTitle", "BugTracker.NET") + " - "
                    + "change password";
            }
            else
            {
                msg.InnerHtml = "";

                if (string.IsNullOrEmpty(password.Value))
                {
                    msg.InnerHtml = "Enter your password twice.";
                }
                else if (password.Value != confirm.Value)
                {
                    msg.InnerHtml = "Re-entered password doesn't match password.";
                }
                else if (!Bug_Util.check_password_strength(password.Value))
                {
                    msg.InnerHtml = "Password is not difficult enough to guess.";
                    msg.InnerHtml += "<br>Avoid common words.";
                    msg.InnerHtml += "<br>Try using a mixture of lowercase, uppercase, digits, and special characters.";
                }
                else
                {


                    string guid = Request["id"];

                    if (string.IsNullOrEmpty(guid))
                    {
                        Response.Write("no guid");
                        Response.End();
                    }

                    string sql = @"
declare @expiration datetime
set @expiration = dateadd(n,-$minutes,getdate())

select *,
	case when el_date < @expiration then 1 else 0 end [expired]
	from emailed_links
	where el_id = '$guid'

delete from emailed_links
	where el_date < dateadd(n,-240,getdate())";

                    sql = sql.Replace("$minutes", Bug_Util.get_setting("RegistrationExpiration", "20"));
                    sql = sql.Replace("$guid", guid.Replace("'", "''"));

                    DataRow dr = DbUtil.get_datarow(sql);

                    if (dr == null)
                    {
                        msg.InnerHtml = "The link you clicked on is expired or invalid.<br>Please start over again.";
                    }
                    else if ((int)dr["expired"] == 1)
                    {
                        msg.InnerHtml = "The link you clicked has expired.<br>Please start over again.";
                    }
                    else
                    {
                        Bug_Util.update_user_password((int)dr["el_user_id"], password.Value);
                        msg.InnerHtml = "Your password has been changed.";
                    }

                }
            }
        }
    }
}
